<style lang="less">
  @import 'articles.less';
</style>
<template>
  <div>
    <Row>
      <Col span="24">
        <Card style="margin-bottom: 10px">
          <Form inline>
            <FormItem style="margin-bottom: 0">
              <Cascader :data="cascaderData" clearable v-model="searchConf.category_id" trigger="hover" placeholder="选择分类"  style="width:220px"></Cascader>
            </FormItem>
            <FormItem style="margin-bottom: 0">
              <Input v-model="searchConf.keywords" placeholder="请输入文章标题"></Input>
            </FormItem>
            <FormItem style="margin-bottom: 0">
              <Button type="primary" @click="search">{{ $t('find_button') }}/{{ $t('refresh_button') }}</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
    <Row>
      <Col span="24">
        <Card>
          <p slot="title" style="height: 32px">
            <Button type="primary" @click="addModal" icon="md-add">{{ $t('add_button') }}</Button>&nbsp;
          </p>
          <div>
            <Table :loading="listLoading" :columns="columnsList" :data="tableData" border disabled-hover></Table>
          </div>
          <div class="margin-top-15" style="text-align: center">
            <Page :total="tableShow.listCount" :current="tableShow.currentPage"
                  :page-size="tableShow.pageSize" @on-change="changePage"
                  @on-page-size-change="changeSize" show-elevator show-sizer show-total></Page>
          </div>
        </Card>
      </Col>
    </Row>
    <Modal  v-model="modalSetting.show" width="80%" :styles="{top: '30px'}" @on-visible-change="doCancel">
      <p slot="header" style="color:#2d8cf0">
        <Icon type="md-alert" />
        <span>新增文章</span>
      </p>
      <Row>
        <Col span="20" push="4">
          <Card dis-hover :bordered="false" :shadow="false" >
            <Form ref="myForm" :rules="ruleValidate" :model="formItem" :label-width="100">
              <FormItem label="文章配图" prop="thumbnail">
                <div class="demo-upload-list" v-if="thumbnail.previewUrl">
                  <img :src="thumbnail.previewUrl">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-trash-outline" @click.native="handleImgRemove()"></Icon>
                  </div>
                </div>
                <input v-if="formItem.thumbnail" v-model="formItem.thumbnail" type="hidden" name="image">
                <Upload ref="thumbnail" type="drag"
                        :action="thumbnail.uploadUrl"
                        :headers="thumbnail.uploadHeader"
                        v-if="!formItem.thumbnail"
                        :format="['jpg','jpeg','png','gif']"
                        name="image"
                        :data="thumbnail.fileData"
                        :max-size="5120"
                        :on-success="handleImgSuccess"
                        :on-format-error="handleImgFormatError"
                        :on-exceeded-size="handleImgMaxSize"
                        :before-upload="handleUpload"
                        :show-upload-list="false"
                        style="display: inline-block;width:128px">
                  <div style="width: 128px;height:128px;line-height: 128px">
                    <Icon type="md-camera" size="30"></Icon>
                  </div>
                </Upload>
              </FormItem>

              <FormItem  label="文章标题" prop="title">
                <Input v-model="formItem.title" placeholder="请输入文章标题"></Input>
              </FormItem>
              <FormItem label="文章来源" prop="source">
                <Input v-model="formItem.source" placeholder="请输入文章来源"></Input>
              </FormItem>
              <FormItem  label="关键字" prop="keywords">
                <Input v-model="formItem.keywords" placeholder="请输入关键字"></Input>
              </FormItem>
              <FormItem label="文章摘要" prop="excerpt">
                <Input type="textarea" :rows="4" v-model="formItem.excerpt" placeholder="请输入摘要"></Input>
              </FormItem>
              <FormItem label="文章内容" >
              <editor ref="editor" :value="formItem.content" @on-change="handleChange"/>
              </FormItem>
            </Form>
          </Card>
        </Col>
        <Col span="4" pull="20">
            <Card :shadow="false" dis-hover>
              <p slot="title">选择分类</p>
              <Tree :check-strictly="true" :data="categoryTree" ref="category" show-checkbox  :multiple="true"></Tree>
            </Card>
        </Col>
      </Row>
      <div slot="footer">
        <Button type="text" @click="cancel" style="margin-right: 8px">取消</Button>
        <Button type="primary" @click="submit" :loading="modalSetting.loading">确定</Button>
      </div>
    </Modal>
    <Modal title="查看大图" v-model="previewVisible" class-name="fl-image-modal">
      <img :src="previewUrl" v-if="previewVisible" style="width: 100%">
    </Modal>
  </div>
</template>
<script>
import Editor from '_c/editor'
import { baseUrl } from '@/libs/api.request'
import { getToken } from '@/libs/util'
import CryptoJS from 'crypto-js'
import expandRow from './table_expand.vue'
import { forEach } from '@/libs/tools'

const editButton = (vm, h, currentRow, index) => {
  return h('Button', {
    props: {
      type: 'primary'
    },
    style: {
      margin: '0 5px'
    },
    on: {
      'click': () => {
        vm.formItem.id = currentRow.id
        vm.formItem.title = currentRow.title
        vm.formItem.keywords = currentRow.keywords
        vm.formItem.excerpt = currentRow.excerpt
        vm.formItem.thumbnail = currentRow.thumbnail
        vm.thumbnail.previewUrl = currentRow.preview_url
        vm.formItem.source = currentRow.source
        vm.formItem.content = currentRow.content
        vm.$refs.editor.setHtml(currentRow.content)
        vm.formItem.category_id = currentRow.category_id
        vm.categoryTree = vm.handleCategory(vm.categoryTree, currentRow.category_id, currentRow.category_path)
        vm.modalSetting.show = true
        vm.modalSetting.index = index
      }
    }
  }, vm.$t('edit_button'))
}
const deleteButton = (vm, h, currentRow, index) => {
  return h('Poptip', {
    props: {
      confirm: true,
      title: '您确定要删除这条数据吗? ',
      transfer: true
    },
    on: {
      'on-ok': () => {
        vm.$easyAjax({ url: 'Article/delete/' + (currentRow.id), method: 'delete' }).then(response => {
          if (response.data.code) {
            vm.getList()
            currentRow.loading = false
          } else {
            vm.$Message.error(response.data.msg)
          }
        })
      }
    }
  }, [
    h('Button', {
      style: {
        margin: '0 5px'
      },
      props: {
        type: 'error',
        placement: 'top',
        loading: currentRow.isDeleting
      }
    }, vm.$t('delete_button'))
  ])
}

export default {
  name: 'articles',
  components: { expandRow, Editor },
  data () {
    return {
      categoryTree: [],
      cascaderValue: [],
      cascaderData: [],
      listLoading: false,
      columnsList: [
        {
          title: 'ID',
          align: 'center',
          key: 'id',
          fixed: 'left',
          width: 100
        },
        {
          title: '文章标题',
          align: 'center',
          minWidth: 320,
          fixed: 'left',
          key: 'title'
        },
        {
          title: '缩略图',
          align: 'center',
          key: 'thumbnail',
          width: 100,
          render: (h, params) => {
            if ((params.row.thumbnail).length > 10) {
              return h('div', [
                h('Icon', {
                  props: {
                    type: 'md-image'
                  },
                  style: {
                    marginRight: '5px',
                    fontSize: '38px',
                    color: '#2d8cf0',
                    cursor: 'pointer'
                  },
                  on: {
                    click: () => {
                      this.handleView(params.row.preview_url)
                    }
                  }
                })
              ])
            } else {
              return h('div', ['未上传'])
            }
          }
        },
        {
          title: '是否发布',
          align: 'center',
          width: 100,
          render: (h, params) => {
            let vm = this
            return h('i-switch', {
              attrs: {
                size: 'large'
              },
              props: {
                'true-value': 1,
                'false-value': 0,
                value: params.row.status
              },
              on: {
                'on-change': function (status) {
                  vm.$easyAjax({ url: 'Article/changeStatus/' + (params.row.id), data: { status: status }, method: 'put' }).then(response => {
                    if (response.data.code) {
                      vm.$Message.success(response.data.msg)
                    } else {
                      vm.$Message.error({
                        content: response.data.msg,
                        duration: 10,
                        closable: true
                      })
                    }
                  })
                }
              }
            }, [
              h('span', {
                slot: 'open'
              }, '是'),
              h('span', {
                slot: 'close'
              }, '否')
            ])
          }
        },
        {
          title: '是否推荐',
          align: 'center',
          width: 100,
          key: 'recommend',
          render: (h, params) => {
            let vm = this
            return h('i-switch', {
              attrs: {
                size: 'large'
              },
              props: {
                'true-value': 1,
                'false-value': 0,
                value: params.row.recommend
              },
              on: {
                'on-change': function (recommend) {
                  vm.$easyAjax({ url: 'Article/changeRecommend/' + (params.row.id), data: { recommend: recommend }, method: 'put' }).then(response => {
                    if (response.data.code) {
                      vm.$Message.success(response.data.msg)
                    } else {
                      vm.$Message.error({
                        content: response.data.msg,
                        duration: 10,
                        closable: true
                      })
                    }
                  })
                }
              }
            }, [
              h('span', {
                slot: 'open'
              }, '是'),
              h('span', {
                slot: 'close'
              }, '否')
            ])
          }
        },
        {
          title: '是否置顶',
          align: 'center',
          width: 100,
          key: 'top',
          render: (h, params) => {
            let vm = this
            return h('i-switch', {
              attrs: {
                size: 'large'
              },
              props: {
                'true-value': 1,
                'false-value': 0,
                value: params.row.top
              },
              on: {
                'on-change': function (top) {
                  vm.$easyAjax({ url: 'Article/changeTop/' + (params.row.id), data: { top: top }, method: 'put' }).then(response => {
                    if (response.data.code) {
                      vm.$Message.success(response.data.msg)
                    } else {
                      vm.$Message.error({
                        content: response.data.msg,
                        duration: 10,
                        closable: true
                      })
                    }
                  })
                }
              }
            }, [
              h('span', {
                slot: 'open'
              }, '是'),
              h('span', {
                slot: 'close'
              }, '否')
            ])
          }
        },
        {
          title: '排序',
          align: 'center',
          width: 120,
          render: (h, params) => {
            let vm = this
            return h('div', [
              h('Input', {
                props: {
                  type: 'number',
                  value: params.row.sort
                },
                on: {
                  'on-change': function (event) {
                    params.row.sort = event.target.value
                    vm.tableData[params.index] = params.row
                    vm.$easyAjax({ url: 'Article/changeSort/' + (params.row.id), data: { value: params.row.sort }, method: 'put' }).then(response => {
                      if (response.data.code) {

                      } else {
                        vm.$Message.error({
                          content: response.data.msg,
                          duration: 10,
                          closable: true
                        })
                      }
                    })
                  }
                },
                style: {
                  width: '100%'
                }
              })
            ])
          }
        },
        {
          title: '创建时间',
          align: 'center',
          width: 180,
          key: 'create_time'
        },
        {
          title: '操作',
          align: 'center',
          width: 200,
          fixed: 'right',
          render: (h, params) => {
            return h('div', [
              editButton(this, h, params.row, params.index),
              deleteButton(this, h, params.row, params.index)
            ])
          }
        }
      ],
      selectApp: 0,
      modalSetting: {
        show: false,
        loading: false,
        index: 0
      },
      previewVisible: false,
      uploadLoading: null,
      previewUrl: '',
      formItem: {
        id: 0,
        title: '',
        category_id: '',
        keywords: '',
        excerpt: '',
        thumbnail: '',
        content: ''
      },
      thumbnail: {
        fileData: { hash: '' },
        uploadUrl: baseUrl + 'Attachment/add',
        uploadHeader: { 'App-Login-Token': getToken() },
        file: null,
        previewUrl: ''
      },
      tableData: [],
      tableShow: {
        currentPage: 1,
        pageSize: 10,
        listCount: 0
      },
      searchConf: {
        type: '',
        keywords: '',
        status: '',
        category_id: []
      },
      checkEditorEmpty: '',
      ruleValidate: {
        title: [
          { required: true, message: '文章标题不能为空', trigger: 'blur' }
        ],
        excerpt: [
          { required: true, message: '摘要不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 处理树形分类子级选中父级展开
    handleCategory (list, selectedCategory, parentPath) {
      let vm = this
      let res = []
      forEach(list, item => {
        let obj = item
        if (parentPath && parentPath.includes(obj.id)) {
          vm.$set(obj, 'expand', true) // 父级展开祖级展开  3级
        }
        if (selectedCategory) {
          if (!item.children && selectedCategory.includes(obj.id)) {
            vm.$set(obj, 'checked', true)
            vm.$set(obj, 'disableCheckbox', false)
          } else {
            vm.$set(obj, 'checked', false)
          }
        }
        if (obj.children) {
          vm.$set(obj, 'disableCheckbox', true)
          obj.children = vm.handleCategory(item.children, selectedCategory, parentPath)
        } else {
          vm.$set(obj, 'disableCheckbox', false)
        }
        res.push(obj)
      })
      return res
    },
    handleView (url) {
      this.previewUrl = url
      this.previewVisible = true
    },
    handleChange (html, text) {
      this.formItem.content = html
      this.checkEditorEmpty = text
    },
    handleUpload (file) {
      let vm = this
      let reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onload = function (evt) {
        var fileString = evt.target.result
        var wordArray = CryptoJS.lib.WordArray.create(fileString)
        var hash = CryptoJS.SHA256(wordArray).toString()
        vm.$easyAjax({ url: 'Attachment/add', data: { hash: hash }, method: 'post' }).then(res => {
          if (res.data.code) {
            vm.$Message.success({ content: '极速闪传成功' })
            vm.formItem.thumbnail = res.data.data[0].fileUrl
            vm.thumbnail.previewUrl = res.data.data[0].previewUrl
          } else {
            vm.autoUpload('thumbnail', file)
          }
        })
      }
      return false
    },
    autoUpload (refs, files) {
      this.uploadLoading = this.$Message.loading({
        content: '上传中...',
        duration: 0
      })
      this.$refs[refs].post(files)
    },
    handleImgFormatError (file) {
      this.$Notice.warning({
        title: '文件类型不合法',
        desc: file.name + '的文件类型不正确，请上传jpg或者png图片。'
      })
    },
    handleImgRemove () {
      this.formItem.thumbnail = ''
      this.thumbnail.previewUrl = ''
    },
    handleImgSuccess (response) {
      this.uploadLoading()
      if (response.code === 1) {
        this.$Message.success(response.msg)
        this.formItem.thumbnail = response.data[0].fileUrl
        this.thumbnail.previewUrl = response.data[0].previewUrl
      } else {
        this.$Message.error(response.msg)
      }
    },
    handleImgMaxSize (file) {
      this.$Notice.warning({
        title: '文件大小不合法',
        desc: file.name + '请上传小于5M的文件。'
      })
    },
    addModal () {
      this.categoryTree = this.handleCategory(this.categoryTree)
      this.modalSetting.show = true
    },
    changePage (page) {
      this.tableShow.currentPage = page
      this.getList()
    },
    changeSize (size) {
      this.tableShow.pageSize = size
      this.getList()
    },
    search () {
      this.tableShow.currentPage = 1
      this.getList()
    },
    cancel () {
      this.modalSetting.show = false
    },
    doCancel (data) {
      if (!data) {
        this.formItem.id = 0
        this.$refs['myForm'].resetFields()
        this.$refs.editor.setHtml('')
        this.formItem.thumbnail = ''
        this.formItem.category_id = ''
        this.formItem.source = ''
        this.formItem.content = ''
        this.thumbnail.previewUrl = ''
        this.modalSetting.loading = false
        this.modalSetting.index = 0
      }
    },
    getList () {
      let vm = this
      let params = {
        page: vm.tableShow.currentPage,
        size: vm.tableShow.pageSize,
        type: vm.searchConf.type,
        keywords: vm.searchConf.keywords,
        category_id: vm.searchConf.category_id
      }
      vm.listLoading = true
      this.$easyAjax({ url: 'Article/index', data: params }).then(response => {
        vm.listLoading = false
        vm.tableData = response.data.data.list
        vm.tableShow.listCount = response.data.data.count
        vm.categoryTree = response.data.data.category_tree
        vm.cascaderData = response.data.data.cascader_data
      })
    },
    submit () {
      let vm = this
      let ruleNodes = this.$refs['category'].getCheckedNodes()
      if (ruleNodes.length === 0) {
        vm.$Message.error('必须选择一个分类')
        return
      }
      let categoryArr = []
      for (var i in ruleNodes) {
        if (ruleNodes[i].children) {
          vm.$Message.error('只能选择“' + (ruleNodes[i].title) + '”的子级分类')
          return
        }
        categoryArr.push(ruleNodes[i].id)
      }
      if (vm.checkEditorEmpty === '') {
        vm.$Message.error('文章内容不能为空')
        return
      }
      let categoryIds = categoryArr.join(',')
      vm.formItem.category_id = categoryIds
      vm.$refs['myForm'].validate((valid) => {
        if (valid) {
          let url = 'Article/add'
          let method = 'post'
          if (vm.formItem.id !== 0) {
            url = 'Article/edit/' + (vm.formItem.id)
            method = 'put'
          }
          vm.modalSetting.loading = true
          vm.$easyAjax({ url: url, data: vm.formItem, method: method }).then(response => {
            vm.modalSetting.loading = false
            if (response.data.code) {
              vm.$Message.success(response.data.msg)
              vm.getList()
              vm.cancel()
            } else {
              vm.$Message.error(response.data.msg)
            }
          }).catch(() => {
            vm.modalSetting.loading = false
          })
        }
      })
    }
  }
}
</script>
